local _, ZLAUTO= ...

ZLAUTO.mainFrame = CreateFrame("Frame", "mainFrame", UIParent) --主框架

local ZL = ZLAUTO.mainFrame
ZL.playerName = UnitName("player")
ZL.MLname = "" --初始化ML名字
local REALM_SEPARATOR_LIST = {}
local cGetItemIconByID, cGetItemInfo
if WOW_PROJECT_ID == 1 then
    cGetItemInfo = C_Item.GetItemInfo
    cGetItemIconByID = C_Item.GetItemIconByID
else --WOW_PROJECT_ID == 11 then
    cGetItemInfo = GetItemInfo
    cGetItemIconByID = GetItemIcon
end
for s in REALM_SEPARATORS:gmatch(".") do tinsert(REALM_SEPARATOR_LIST, s) end

--背景，测试用
function ZL.background(frame)
    frame.background = frame:CreateTexture(nil, "BACKGROUND")
    frame.background:SetAllPoints(frame) -- 让纹理覆盖整个Frame
    frame.background:SetColorTexture(math.random(), math.random(), math.random()) -- 设置为随机颜色
end

--设置消息前缀为[ZL]
function ZL.Prefix(...)
    local prefix = string.format("|cffffd60c%s|r", "[ZL]")
    return string.join(" ", prefix, tostringall(...))
end

--定义空元表
function ZL.emptytable(...)
    local logTableRequests = false
    local tables = {}
    local meta = {
        __index = {
            Release=function(t,noRecursion)
                if not noRecursion then
                    for key,val in pairs(t) do
                        if (type(val) == "table") and (getmetatable(val) == "TempTable") then
                            val:Release()
                        end
                    end
                end
                table.wipe(t)
                if not tContains(tables,t) then
                    tinsert(tables,t)
                end
            end,
        },
        __metatable = "TempTable",
    }
    if logTableRequests then
        TempTables_RequestLog = {}
    end
    local t = tremove(tables) or setmetatable({},meta)
    for i=1,select('#',...) do
        t[i] = (select(i,...))
    end
    if logTableRequests then
        local tostrT = tostring(t)
        TempTables_RequestLog[tostrT] = TempTables_RequestLog[tostrT] or {}
        tinsert(TempTables_RequestLog[tostrT],debugstack())
    end
    return t
end
-- 团队团长
function ZL.IsRaidOfficer()
	return IsInRaid() and UnitIsRaidOfficer("player")
end
--小队队长
function ZL.IsRaidLeader()
	return IsInRaid() and UnitIsGroupLeader("player")
end
--是否拥有拾取权限(ML权限)，默认为玩家自己
function ZL.PlayerIsML(playerName)
    if IsInRaid() then
        playerName = playerName or "player"
        local lootMethod, partyMaster, raidMaster = GetLootMethod()
        if lootMethod == "master" then
            if raidMaster == UnitInRaid(playerName) then
                return true
            end
        end
    end
    return false
end
--战利品窗口槽是否为物品：0表示没有东西，1表示为物品，2表示为钱
function ZL.LootSlotIsItem(i)
	return (GetLootSlotType(i) == 1)
end
--拍卖倒计时，默认拍卖时间3600秒
function ZL.CountDown(index, endtime)
    local Frame1 = ZL.AuctionFrame.entries[index].Frame1
    if Frame1:GetParent().maxAutoBid then
        Frame1.bidbox:Disable()
        Frame1.bidBtn:Disable()
    else
        Frame1.bidbox:Enable()
        Frame1.bidBtn:Enable()
    end
    Frame1.autobidBtn:Enable()
    Frame1.MLframe.PauseBtn:Enable()
    Frame1.MLframe.CancelBtn:SetText("取消")
    Frame1.MLframe.CountDownBtn:Enable()
    Frame1.MLframe.reverseBidBtn:Enable()
    endtime = endtime or 3600
    Frame1.timer.updateframe:Show()
    Frame1.timer.oneMinuteWarn = false
    Frame1.timer:SetCooldown(GetTime(), endtime)
end
-- 如果GetUnitName不能解析名字为unitID，需我们自己的定义，手动解析
function ZL.localNameOnly(name)
	for _, s in ipairs(REALM_SEPARATOR_LIST) do
		local i = name:find(s, 1, true)
		if i then name = name:sub(1, i - 1) end
	end
	return name
end

--仅在团队中使用,自定义手动解析玩家名字
function ZL.pruneCrossRealm(name)
	return GetUnitName(name, true) or ZL.localNameOnly(name)
end
--创建默认按钮
function ZL.CreateButton(ButtonName, parent, ButtonText, point, relativeto, relativePoint, offsetX, offsetY, Width, Height, fontSize)
	offsetX = offsetX or 0
	offsetY = offsetY or 0
	Width = Width or 70
	Height = Height or 24
	fontSize = fontSize or 13
	local btn = CreateFrame("Button", ButtonName, parent, "UIPanelButtonTemplate")
	btn:SetText(ButtonText)
	btn:SetSize(Width, Height)
	local fontString = btn:GetFontString()
	fontString:SetFont(GameFontNormal:GetFont(), fontSize)
	btn:SetPoint(point, relativeto, relativePoint, offsetX, offsetY)
	return btn
end

--重写滑动条鼠标滚动事件
function ZL.ScrollFrame_OnMouseWheel(self, delta)
    local newValue = self:GetVerticalScroll() - (delta * 20)
    if newValue < 0 then
        newValue = 0
    elseif newValue > self:GetVerticalScrollRange() then
        newValue = self:GetVerticalScrollRange()
    end
    self:SetVerticalScroll(newValue)
end

--更新拍卖主窗口
function ZL.UpdateAuctionFrame()
    local height = 0
    local content = ZL.AuctionFrame.scrollFrame.content
    for _, frame in ipairs(auctionFrames) do
        if frame:IsShown() then
            frame:SetPoint("TOPLEFT", content, "TOPLEFT", 0, -height)
            height = height + frame:GetHeight()
        end
    end
    content:SetHeight(height) --设置滚动放置区域高度
end

--根据值查询索引号,只能查询到第一个出现的
function ZL.tableIndex(myTable, targetValue)
    for i, value in ipairs(myTable) do
        if value == targetValue then
            return i
        end
    end
end
--根据itemId和itemindex获取数据库中是否已存在该拍卖物品
function ZL.FetchDataFromItemId(itemId, itemindex)
    if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
        for index, data in ipairs(ZL_CURRENT.auctionlist) do
            if (data.itemId == itemId) and (data.itemindex == itemindex) then --注意匹配时数据类型是否一致
                return data, index
            end
        end
    end
    print("没有数据")
    return nil, nil
end
--按钮点击间隔时间
function ZL.btnDelay(self)
    self:Disable()
    C_Timer.After(ZL.opt.buttonReenableDelay, function()
        self:Enable()
    end)
end
--没被忽略情况下，拍卖状态的物品个数:拍卖中，等待拍卖，成功，流拍, 忽略
function ZL.auctionStateCount()
    local auctioningCount = 0
    local waitingCount = 0
    local successCount = 0
    local failedCount = 0
    local lgnoreCount = 0
    for _, frame in auctionFrames do
        if frame.lgnore then
            lgnoreCount = lgnoreCount + 1
        else
            if frame.state == "auctioning" then
                auctioningCount = auctioningCount + 1
            elseif frame.state == "waiting" then
                waitingCount = waitingCount + 1
            elseif frame.state == "success" then
                successCount = successCount + 1
            elseif frame.state == "failed" then
                failedCount = failedCount + 1
            end
        end
    end
    return auctioningCount, waitingCount, successCount, failedCount, lgnoreCount
end
--通过itemId获取数组表的索引
function ZL.GetIndex(table, itemId)
    for index, data in ipairs(table) do
        if data.itemId == itemId then
            return index
        end
    end
    return nil
end

--获取起拍价和每次最低加价，优先顺序：独立的物品设置，按照物品等级设置，默认设置
function ZL.GetStartAndIncrementBid(itemId)
	local index = ZL.GetIndex(ZL_SETTING["itemIdSetting"], itemId)
    if index then
        return ZL_SETTING["itemIdSetting"][index].startbid, ZL_SETTING["itemIdSetting"][index].increment
    end
	local ilvl = (select(4, cGetItemInfo(itemId))) --物品装等C_Item.GetItemInfo
	if ilvl then
		for _, d in ipairs(ZL_SETTING["itemLevelSetting"]) do
			if (d.minLevel <= ilvl) and (d.maxLevel >= ilvl) then
				return d.startbid, d.increment
			end
		end
	end
	return ZL.opt.startBid, ZL.opt.increment --全局默认值
end
--设置物品子拍卖窗口是显示还是隐藏
function ZL.ItemAuctionFrameIsShown(data)
    local tabId = ZL.AuctionFrame.tableId
    if tabId == 1 then
        if (not data.lgnore) and (data.state == "auctioning") then
            return true
        else
            return false
        end
    elseif tabId == 2 then
        if (not data.lgnore) and (data.state == "success") then
            return true
        else
            return false
        end
    elseif tabId == 3 then
        if (not data.lgnore) and (data.state == "failed") then
            return true
        else
            return false
        end
    elseif tabId == 4 then
        if data.lgnore then
            return true
        else
            return false
        end
    elseif tabId == 5 then
        if (not data.lgnore) and (data.state == "waiting") then
            return true
        else
            return false
        end
    end
end

--获取正在拍卖的物品个数，如果有多个，则返回个数和最后1个拍卖物品的index，暂停拍卖的也不属于拍卖中的
function ZL.GetAuctioningCount()
    local num = 0
    local index = nil
    if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist then
        for i, data in ipairs(ZL_CURRENT.auctionlist) do
            if data.state == "auctioning" and (not data.isPaused) then
                num = num + 1
                index = i
            end
        end
    end
    return num, index
end
-- 定义一个函数来判断一串数字是否由相同的数字组成
function ZL.isAllSameDigits(numberString)
    -- 获取字符串的第一个字符
    local firstChar = numberString:sub(1, 1)
    -- 使用模式匹配来检查字符串是否只包含这个字符
    local pattern = "^" .. firstChar .. "+$"
    return numberString:match(pattern) ~= nil
end

--将出价者列表按照出价金额从大到小排序
function ZL.tableSort(tab)
    if #tab > 1 then
        table.sort(tab, function (a, b)
            return a.bidamount > b.bidamount
        end)
    end
end

--是否过滤物品
function ZL.isFilterItem(itemId)
    for _, data in ipairs(ZL_SETTING["filterItemId"]) do
        if data.itemId == itemId then
            return true
        end
    end
end
--字符串固定长度，如不够，自动在前面填充
function ZL.pad_left(str, length)
    return string.format("%" .. length .. "s", str)
  end

--自动出价
function ZL.autoBid(index, maxAutoBid)
    local curAuctionList = ZL_CURRENT.auctionlist[index]
    if maxAutoBid and (not curAuctionList.isPaused) then
        local bidderlist = ZL_CURRENT.auctionlist[index].bidderlist
        ZL.tableSort(bidderlist)
        local isSelf = false
        for i = 1, math.min(curAuctionList.itemCount, #bidderlist) do
            if bidderlist[i].bidder == UnitName("player") then
                isSelf = true
                break
            end
        end
        if (not isSelf) then
            local tarbidamount = 0
            if bidderlist[curAuctionList.itemCount] then
                tarbidamount = bidderlist[curAuctionList.itemCount].bidamount + curAuctionList.bidIncrement
            else
                tarbidamount = curAuctionList.startbidamount
            end
            if tarbidamount <= maxAutoBid then
                SendChatMessage(curAuctionList.itemlink .. tarbidamount, "RAID")
            else
                local f = ZL.AuctionFrame.entries[index]
                f.Frame1.autobidBtn:Click()
            end
        end
    end
end
--同步配置文件全局参数
function ZL.TransmitAddonInfo_Pro()
    local data = {
        auctionTimerRefresh = ZL.opt.auctionTimerRefresh,
        auctionTimer = ZL.opt.auctionTimer,
    }
    MyAddon:TransmitAddonInfo("AUTOAUC PRO", data)
end
--提示消息
function ZL.GameTooltipShow(self, point, relativePoint, offsetX, offsetY)
    offsetX = offsetX or 0
    offsetY = offsetY or 0
    GameTooltip:ClearAllPoints()
    GameTooltip:ClearLines()
    GameTooltip:SetOwner(self, "ANCHOR_NONE")
    GameTooltip:SetPoint(point, self, relativePoint, offsetX, offsetY)
end
--将秒转换成时间格式
function ZL.ConvertSecondsToTime(seconds)
    local hours = math.floor(seconds / 3600)
    local minutes = math.floor((seconds % 3600) / 60)
    local remainingSeconds = seconds % 60

    if hours > 0 then
        return string.format("%02d:%02d:%02d", hours, minutes, remainingSeconds)
    elseif hours == 0 and minutes > 0 then
        return string.format("%02d:%02d", minutes, remainingSeconds)
    else
        return string.format("%d", remainingSeconds)
    end
end
--获取装备交易剩余时间
function ZL.GetRemainingTradeTime()
    local RemainingTradeItems = {}
    for bag = 0, NUM_BAG_SLOTS do
        for slot = 1, C_Container.GetContainerNumSlots(bag) do
            local itemLink = C_Container.GetContainerItemLink(bag, slot)
            if itemLink then
                if (not ZL.ToolTip) then
                    ZL.ToolTip = CreateFrame("GameTooltip", "TradeTimeRemainingTooltip", nil, "GameTooltipTemplate")
                end
                ZL.ToolTip:SetOwner(UIParent, "ANCHOR_NONE")
                ZL.ToolTip:ClearLines()
                ZL.ToolTip:SetBagItem(bag, slot)
                for i = 1, ZL.ToolTip:NumLines() do
                    local text = _G["TradeTimeRemainingTooltipTextLeft"..i]:GetText()
                    if text then
                        local timeRemaining = text:match(BIND_TRADE_TIME_REMAINING:gsub("%%s", "(.+)"))
                        if timeRemaining then
                            local hour = tonumber(timeRemaining:match("(%d+)" .. "小时")) or 0
                            local min = tonumber(timeRemaining:match("(%d+)" .. "分钟")) or 0
                            table.insert(RemainingTradeItems, {
                                itemLink=itemLink, timeRemaining=timeRemaining, hour=hour, min=min
                            })
                            break
                        end
                    end
                end
            end
        end
    end
    if #RemainingTradeItems > 0 then
        table.sort(RemainingTradeItems, function (a, b)
            return (a.hour*60 + a.min) < (b.hour*60 + b.min)
        end)
    end
    local text = "|cffffd100交易剩余时间清单：|r\n"
    for _, data in ipairs(RemainingTradeItems) do
        if (data.hour*60 + data.min) <= 30 then
            text = text .. data.itemLink .. ":|cffff0000" .. data.timeRemaining .. "|r\n"
        else
            text = text .. data.itemLink .. ":" .. data.timeRemaining .. "\n"
        end
    end
    ZL.RemainingTradeTimeFrame.RemainingTradeTimeText:SetText(text)
end

function ZL.GetCurrentRoster()
    local roster = {{},{},{},{},{},{},{},{}} --初始化8个小队
    for i = 1, GetNumGroupMembers() do
        local name, _, subgroup = GetRaidRosterInfo(i)
        if name then
            table.insert(roster[subgroup], name)
        end
    end
    return roster
end
--是否需要邮寄工资
function ZL.IsNeedMail(name)
    local nameIsExist = false
    if ZL_CURRENT["mailPlayers"] and #ZL_CURRENT["mailPlayers"] > 0 then
        for _, _name in ipairs(ZL_CURRENT["mailPlayers"]) do
            if _name == name then
                nameIsExist = true
                break
            end
        end
    end
    return nameIsExist
end
function ZL.padZeros(num, tarbidamount)
    local numStr = tostring(num)
    local currentLength = #numStr
    local length = #tostring(tarbidamount)
    -- 如果当前长度已经大于或等于要求的长度，则直接返回原数字字符串
    if currentLength >= length then
        return tonumber(numStr)
    end
    -- 计算需要添加的零的数量
    local zerosToAdd = length - currentLength
    -- 创建一个包含需要数量零的字符串
    local zeros = string.rep("0", zerosToAdd)
    -- 将零添加到数字字符串的后面
    local paddedNumStr = numStr .. zeros
    local step = tarbidamount <= 10000 and 1000 or 10000
    if (tonumber(paddedNumStr) < tarbidamount) and (tonumber(paddedNumStr .. "0") - tarbidamount <= step) then
        paddedNumStr = paddedNumStr .. "0"
    end
    return tonumber(paddedNumStr)
end

function ZL.msg_gsub(msg)
    local cmsg = msg:gsub("%s", "")
    cmsg = cmsg:gsub("。", ".")
    cmsg = cmsg:gsub("万", "w")
    cmsg = cmsg:gsub("千", "k")
    cmsg = cmsg:gsub("一", "1")
    cmsg = cmsg:gsub("二", "2")
    cmsg = cmsg:gsub("三", "3")
    cmsg = cmsg:gsub("四", "4")
    cmsg = cmsg:gsub("五", "5")
    cmsg = cmsg:gsub("六", "6")
    cmsg = cmsg:gsub("七", "7")
    cmsg = cmsg:gsub("八", "8")
    cmsg = cmsg:gsub("九", "9")
    cmsg = cmsg:gsub("两", "2")
    cmsg = cmsg:gsub("伍", "5")
    return cmsg
end


function  ZL.utf8len(s)
    local len = 0
    local currentIndex = 1
    local bytes = string.len(s)
    while currentIndex <= bytes do
        local char = string.byte(s, currentIndex)
        if char > 0 and char <= 127 then
            currentIndex = currentIndex + 1
        elseif char >= 194 and char <= 223 then
            currentIndex = currentIndex + 2
        elseif char >= 224 and char <= 239 then
            currentIndex = currentIndex + 3
        elseif char >= 240 and char <= 244 then
            currentIndex = currentIndex + 4
        end
        len = len + 1
    end
    return len
end

--将汉字数字转换为数字
function ZL.convert_all_chinese_numbers(input_str)
    -- 创建一个映射表，将汉字数字转换为阿拉伯数字
    local chinese_numbers = {
        ["两"] = 2,
        ["零"] = 0,
        ["一"] = 1,
        ["二"] = 2,
        ["三"] = 3,
        ["四"] = 4,
        ["五"] = 5,
        ["六"] = 6,
        ["七"] = 7,
        ["八"] = 8,
        ["九"] = 9,
        ["十"] = 10,
        ["百"] = 100,
        ["千"] = 1000,
        ["万"] = 10000,
        ["亿"] = 100000000
    }
    -- 将汉字数字转换为阿拉伯数字
    local function chinese_to_arabic(chinese_str)
        local result = 0
        local temp_num = 0
        local last_unit = 1 -- 上一个单位
    
        for i = 1, #chinese_str-2, 3 do
            local char = chinese_str:sub(i, i+2)
            local num = chinese_numbers[char]
    
            if num < 10 then
                temp_num = num
            else
                if num > last_unit then
                    result = result + (temp_num == 0 and 1 or temp_num) * num
                else
                    result = result + temp_num * num
                end
                temp_num = 0
                last_unit = num
            end
        end
    
        -- 处理最后一个数字
        if temp_num ~= 0 then
            result = result + temp_num
        end
    
        return result
    end
    local pattern = "[两零一二三四五六七八九十百千万亿]+"
    local result = input_str:gsub(pattern, function(cn_num)
        if cn_num then
            return tostring(chinese_to_arabic(cn_num))
        end
    end)
    return result
end